package com.woniu.day8.service.Impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import com.woniu.day8.service.ALiYunOssSevice;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 文件上传 业务层案例
 */
@Service
public class ALiYunOssSeviceImpl implements ALiYunOssSevice {

    @Value("${aliyun.oss.file.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.file.keyid}")
    private String accessKeyId;

    @Value("${aliyun.oss.file.keysecret}")
    private String accessKeySecret;

    @Value("${aliyun.oss.file.bucketname}")
    private String bucketName;

    @Override
    public String updateAvatar(MultipartFile file, String username) throws IOException {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 指定文件夹路径，例如: avatars/用户名/文件名
            String folderPath = "avatars/" + username + "/";

            // 生成唯一文件名
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();

            // 完整的对象键（包含文件夹路径）
            String objectName = folderPath + fileName;

            // 上传文件
            ossClient.putObject(bucketName, objectName, file.getInputStream());

            // 返回访问URL
            return "https://" + bucketName + "." + endpoint + "/" + objectName;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
